import React, { forwardRef, useEffect, useImperativeHandle, useState } from 'react';

import {
  Button,
  DatePicker,
  Form,
  Input,
  Modal,
  Radio,
  Tag,
  Select,
  InputNumber,
  message,
  Row,
  Col,
} from 'antd';
import { modalLayoutLg, modalLayoutSm } from '@/config/layout';
import { request } from 'umi';
const DictModal = (props: any, refs: any) => {
  const [form] = Form.useForm();
  // const [fileList,setfileList] = useState([]);
  const [measureClassData, setmeasureClassData] = useState([]);
  const { setFieldsValue, resetFields } = form;
  const [columns, setcolumns] = useState([]);
  const [code, setCode] = useState('');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const { TextArea } = Input;
  const [detailData, setdetailData] = useState({});
  //显示弹窗
  const showModal = () => {
    setIsModalVisible(true);
  };

  //取消
  const handleCancel = () => {
    setIsModalVisible(false);
    setCode('');
    resetFields();
    props.callback && props.callback();
  };
  const getFields = () => {
    request('/data/dynamic/query', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: { "apiID": "DMT_MNG_01", "apiParam": { "api_id": "DMT_MNG_02_01" } },
    }).then((res) => {
      const data = res.data;
      const apiParamStr = data.data['0']['api_param'] ? data.data['0']['api_param'] : '';
      const apiParam = data.data['0']['api_param'] ? JSON.parse(data.data['0']['api_param']) : {};


      console.log(apiParam.paramList)
      const detailDataNew = {};
      apiParam.paramList.map((e) => {
        detailDataNew[e.name] = '';
      })
      setdetailData(detailDataNew)
      setcolumns(apiParam.paramList)
    });
  }
  useEffect(() => {
    getFields();
  }, [])
  //确定
  const handleOk = () => {
    form
      .validateFields()
      .then((vals) => {
        let Obj = form.getFieldsValue();
        Obj = {
          ...Obj,
        };

        const url = code ? '/data/dynamic/execute' : 'data/dynamic/execute';
        const apiID = code ? 'DMT_MNG_02_02' : 'DMT_MNG_02_01'
        if (code) {
          Obj.api_id = code;
        } else {

        }
        // for (let i in Obj) {
        //   if (Obj[i] === undefined) {
        //     Obj[i] = null;
        //   }
        // }
        request(url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          data: {
            apiID: apiID,
            apiParam: Obj
          },
        }).then((res) => {
          message.success(res?.meta?.msg);
          setIsModalVisible(false);
          handleCancel();
        });
      })
      .catch((info) => { });
  };

  const getDetail = (id: any) => {
    request('/data/dynamic/query', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: { "apiID": "DMT_MNG_02_04", "apiParam": { "api_id": id } },
    }).then((res) => {
      let data = res['data']['data'][0];
      setdetailData(data);
      setTimeout(() => {
        window['setFieldsValue'] = setFieldsValue;
        setFieldsValue({
          ...data
        });
      }, 1000);
      showModal();
    });
  };

  useImperativeHandle(refs, () => ({
    init: (id: any, record: any) => {
      if (id) {
        setCode(id);
        getDetail(id);
      } else {
        resetFields();
        showModal();
      }

      // setfileList([]);
    },
  }));

  return (
    <Modal
      title={code === '' ? '新增' : '编辑'}
      visible={isModalVisible}
      onOk={handleOk}
      onCancel={handleCancel}
      centered
      width={1000}
      maskClosable={false}
      bodyStyle={{
        maxHeight: window.innerHeight - 150,
        overflowY: 'auto',
      }}
    >
      <Form form={form} layout="vertical" {...modalLayoutSm}>
        {
          columns.map((e, i) => {
            let item = e;
            let type = e['element']['type'];
            return <Form.Item
              name={item['name']}
              key={i}
              extra={item['element']['tip'] || ''}
              label={item['element']['label']}
              // label = {item['name']}
              rules={[{ required: item['element']['require'], message: type == 'radio' ? '请选择' + item['element']['label'] : '请输入' + item['element']['label'] }]}
            >
              {
                type == 'text' && <Input value={detailData[item['name']]} onChange={(e) => {
                  let name = item['name']
                  setFieldsValue({
                    [name]: e.target.value
                  })
                  setdetailData({
                    ...detailData,
                    ...{
                      [name]: e.target.value
                    }
                  })
                }} />
              }
              {
                type == 'textarea' && <Input.TextArea rows={item['element']['rows'] || 1} value={detailData[item['name']]} onChange={(e) => {
                  let name = item['name']
                  setFieldsValue({
                    [name]: e.target.value
                  })
                  setdetailData({
                    ...detailData,
                    ...{
                      [name]: e.target.value
                    }
                  })
                }} />
              }
              {
                (type == 'radio' && <div>
                  {
                    item?.element?.option_url ? <DefineRdaio value={detailData[item['name']]} onChange={(e) => {
                      let name = item['name']
                      setFieldsValue({
                        [name]: e.target.value
                      })
                      setdetailData({
                        ...detailData,
                        ...{
                          [name]: e.target.value
                        }
                      })
                    }} {...item.element.option_url} /> : <Radio.Group value={detailData[item['name']]} onChange={(e) => {
                      let name = item['name']
                      setFieldsValue({
                        [name]: e.target.value
                      })
                      setdetailData({
                        ...detailData,
                        ...{
                          [name]: e.target.value
                        }
                      })
                    }}>
                      {
                        item.element.option && item.element.option.map((el, il) => {
                          return <Radio key={'kk' + il} value={el.value}>
                            {el.label}
                          </Radio>
                        })
                      }
                    </Radio.Group>
                  }

                </div>)
              }
              {
                type == 'password' && <Input value={detailData[item['name']]} type='password' onChange={(e) => {
                  let name = item['name']
                  setFieldsValue({
                    [name]: e.target.value
                  })
                  setdetailData({
                    ...detailData,
                    ...{
                      [name]: e.target.value
                    }
                  })
                }} />
              }
            </Form.Item>
          })
        }
      </Form>
    </Modal>
  );
};
const AddMCom = forwardRef(DictModal);

export default AddMCom;
